using AutoMapper;
using B.S.RbacData.Infrastructure;
using MediatR;
using Microsoft.EntityFrameworkCore;
using SupplierCustomerManagement.Domain.Entities;
using B.S.RbacData.ErrorCode;
using SupplierCustomerManagement.Read.API.Applications.Commands.servicepersonals;

namespace SupplierCustomerManagement.Read.API.Applications.CommandHandlters.servicepersonals
{
    /// <summary>
    /// 获取服务人员列表查询处理器
    /// </summary>
    public class GetServicePersonalsQueryHandler : IRequestHandler<GetServicePersonalsQuery, ApiPaging<ServicePersonalListDto>>
    {
        private readonly IBaseRepository<ServicePersonnel> _servicePersonalRepository;
        private readonly IMapper _mapper;
        private readonly ILogger<GetServicePersonalsQueryHandler> _logger;

        public GetServicePersonalsQueryHandler(
            IBaseRepository<ServicePersonnel> servicePersonalRepository,
            IMapper mapper,
            ILogger<GetServicePersonalsQueryHandler> logger)
        {
            _servicePersonalRepository = servicePersonalRepository;
            _mapper = mapper;
            _logger = logger;
        }

        /// <summary>
        /// 处理获取服务人员列表查询
        /// </summary>
        /// <param name="request">查询请求</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>分页查询结果</returns>
        public async Task<ApiPaging<ServicePersonalListDto>> Handle(GetServicePersonalsQuery request, CancellationToken cancellationToken)
        {
            try
            {
                _logger.LogInformation("开始查询服务人员列表，页码: {PageIndex}, 每页大小: {PageSize}", 
                    request.PageIndex, request.PageSize);

                // 构建查询条件
                var query = _servicePersonalRepository.GetAll()
                    .Where(sp => !sp.IsDeleted); // 排除已删除的记录

                // 应用筛选条件
                query = ApplyFilters(query, request);

                // 获取总数量
                var totalCount = await query.CountAsync(cancellationToken);

                // 计算总页数
                var pageCount = (int)Math.Ceiling((double)totalCount / request.PageSize);

                // 分页查询
                var servicePersonals = await query
                    .OrderByDescending(sp => sp.CreatedTime) // 按创建时间倒序排列
                    .ThenByDescending(sp => sp.IsDefault) // 默认服务人员优先显示
                    .Skip((request.PageIndex - 1) * request.PageSize)
                    .Take(request.PageSize)
                    .ToListAsync(cancellationToken);

                // 映射到DTO
                var servicePersonalDtos = _mapper.Map<List<ServicePersonalListDto>>(servicePersonals);

                _logger.LogInformation("成功查询服务人员列表，总数量: {TotalCount}, 当前页数量: {CurrentPageCount}", 
                    totalCount, servicePersonalDtos.Count);

                return new ApiPaging<ServicePersonalListDto>
                {
                    code = ResultEnumCode.Ok,
                    message = "查询成功",
                    data = default,
                    TotalCount = totalCount,
                    PageCount = pageCount,
                    PageData = servicePersonalDtos
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "查询服务人员列表时发生异常");
                
                return new ApiPaging<ServicePersonalListDto>
                {
                    code = ResultEnumCode.fails,
                    message = $"查询服务人员列表时发生异常: {ex.Message}",
                    data = default,
                    TotalCount = 0,
                    PageCount = 0,
                    PageData = new List<ServicePersonalListDto>()
                };
            }
        }

        /// <summary>
        /// 应用筛选条件
        /// </summary>
        /// <param name="query">查询对象</param>
        /// <param name="request">查询请求</param>
        /// <returns>应用筛选条件后的查询对象</returns>
        private IQueryable<ServicePersonnel> ApplyFilters(IQueryable<ServicePersonnel> query, GetServicePersonalsQuery request)
        {
            // 关联实体ID筛选
            if (request.RelatedEntityId.HasValue)
            {
                query = query.Where(sp => sp.RelatedEntityId == request.RelatedEntityId.Value);
            }

            // 关联实体类型筛选
            if (!string.IsNullOrWhiteSpace(request.RelatedEntityType))
            {
                query = query.Where(sp => sp.RelatedEntityType == request.RelatedEntityType);
            }

            return query;
        }
    }
}